<template>
  <!--地图容器-->
  <div>
    <div id="allmap"></div>

    <div style="z-index: 999;position: absolute;top:3vh;left: 1vw">
      <Row>
        <Col span="10">
        <Select v-model="type" style="width:140px" placeholder="选择类型">
          <Option v-for="item in cityList" :value="item.value" :key="item.value">{{ item.label }}</Option>
        </Select>
        </Col >
        <Col span="12">
        <Input v-model="keyWords" placeholder="请输入搜索关键字" ></Input>
        </Col >
        <Col span="2">
        <Button type="primary" icon="ios-search"></Button>
        </Col >

      </Row>


    </div>

    <!--<div style="z-index: 999;position: absolute;top:1vh;right: 18vw">-->
      <!--<Button @click.prevent.stop="efAdd()">添加电子围栏</Button>-->
      <!--<Button @click.prevent.stop="efDelete()">删除电子围栏</Button>-->
      <!--<Button @click.prevent.stop="efAlarm()">越界检查</Button>-->
    <!--</div>-->
    <div style="z-index: 999;position: absolute;top:3vh;right: 3vw">
      <Poptip title="图层管理" placement="left-start" width="160px">
        <Icon type="ios-list" size="32"></Icon>
        <div slot="content" >
          <CheckboxGroup v-model="social" style="display:flex;flex-direction:column ">
            <Checkbox class="checkItem" label="twitter">
              <span>气化站</span>
            </Checkbox>
            <Checkbox class="checkItem" label="facebook">
              <span>加气站</span>
            </Checkbox>
            <Checkbox class="checkItem" label="github">
              <span>配送站</span>
            </Checkbox>
            <Checkbox class="checkItem" label="twitter">
              <span>消防力量</span>
            </Checkbox>
            <Checkbox class="checkItem" label="facebook">
              <span>医疗力量</span>
            </Checkbox>
            <Checkbox class="checkItem" label="github">
              <span>槽车</span>
            </Checkbox>
          </CheckboxGroup>
        </div>
      </Poptip>
    </div>

    <Modal
      v-model="historyTrace"
      title="车辆历史轨迹"
      width="900"
      :closable="true">
      <div slot="header" id="header">
        <Row>
          <Col span="10">
          历史轨迹
          </Col>
          <Col span="10">
          <div onload="init();">
            <Checkbox v-model="single">画面跟随</Checkbox>
            <Button type="primary">播放</Button>
            <Button type="primary">暂停</Button>
            <Button type="primary">停止</Button>
          </div>
          </Col>
        </Row>
      </div>
      <Row class="modalBody">
        <Col span="5">
        <p>车牌号</p>
        <p>{{carNumber}}</p>
        <p>历史订单</p>
        <RadioGroup v-model="vertical" vertical @on-change="showTrace">
          <Radio :label="item.number" :key="item.number" v-for="item in list">
            <span>{{item.number}}</span>
          </Radio>
        </RadioGroup>
        </Col>
        <Col span="19" id="historyMap" class="modalBody"></Col>
      </Row>
      <div slot="footer"></div>
    </Modal>
  </div>
</template>
<script type="text/ecmascript-6">
  //import api from '@/fetch/api';
  import car from '@/images/amap/car.png';
  import warning from '@/images/amap/warning.gif';
  import Vue from 'vue'


  export default {
    data () {
      return {
        cityList: [
          {
            value: 'jiaqi',
            label: '加气站'
          },
          {
            value: 'qihua',
            label: '气化站'
          },
          {
            value: 'peisong',
            label: '配送站'
          },
          {
            value: 'xiaofang',
            label: '消防力量'
          },
          {
            value: 'yiliao',
            label: '医疗力量'
          },
          {
            value: 'caoche',
            label: '槽车'
          }
        ],
        type: '',
        keyWords:'',
        social: ['facebook', 'github'],
        historyTrace: false,
        single:false,
        carNumber:'浙F363747',
        list: [
          {
            number: '922110',
          },
          {
            number: '2822110',
          },
          {
            number: '2272110',
          },
          {
            number: '2622110',
          }
        ],
        vertical:'',
        points:[],
        start:{},
        historyMap:{},
        map:{},
        carMarker:null,
        alarmMarker:null,
        overlays:[],
        mlnglat:[],
        styleOptions:{
          strokeColor: "red",
          fillColor: "red",
          strokeWeight: 3,
          strokeOpacity: 0.8,
          fillOpacity: 0.6,
          strokeStyle: 'solid'
        },
        customerInfo:{
          name:'还未登录'
        }
      }
    },
    mounted() {
      //this.customerInfo = api.isEmptyObject(JSON.parse(api.getCookie('customerInfo')))?{name:'还未登录'}:JSON.parse(api.getCookie('customerInfo'));
      console.log(JSON.stringify(this.customerInfo));
      let $this = this;
      this.map = new BMap.Map("allmap", {enableMapClick: false});    // 创建Map实例,并关闭底图可点功能
      this.map.centerAndZoom(new BMap.Point(120.757278, 30.758204), 15);  // 初始化地图,设置中心点坐标和地图级别
      this.map.setCurrentCity("嘉兴");          // 设置地图显示的城市 此项是必须设置的
      this.map.enableScrollWheelZoom(true);     //开启鼠标滚轮缩放

//      this.map.addControl(new BMap.NavigationControl());//左上角，添加默认缩放平移控件
      this.map.enableKeyboard(true);//启动键盘操作

      //版权
//      var bs = this.map.getBounds();   //返回地图可视区域
//      var cr = new BMap.CopyrightControl({anchor: BMAP_ANCHOR_BOTTOM_RIGHT});
//      this.map.addControl(cr); //添加版权控件
//      cr.addCopyright({
//        id: 1,
//        content: "<p  style='background:#ffffff;opacity: 0.5'>2011-2017 &copy; 浙江亚达公司</p>",
//        bounds: bs
//      });

      //鼠标绘制完成回调方法   获取各个点的经纬度
//      var overlaycomplete = function (e) {
//        $this.overlays.push(e.overlay);
//        var path = e.overlay.getPath();//Array<Point> 返回多边型的点数组
//        for (var i = 0; i < path.length; i++) {
//          $this.mlnglat.push(`lng:${path[i].lng},lat:${path[i].lat}`);
//          console.log($this.mlnglat);
//        }
//      };


      //实例化鼠标绘制工具
//      var drawingManager = new BMapLib.DrawingManager(this.map, {
//        isOpen: false, //是否开启绘制模式
//        enableDrawingTool: true, //是否显示工具栏
//        drawingToolOptions: {
//          anchor: BMAP_ANCHOR_TOP_RIGHT, //位置
//          offset: new BMap.Size(5, 5), //偏离值
//          scale:0.7,
//          drawingModes:[
//            BMAP_DRAWING_MARKER,
//            //BMAP_DRAWING_CIRCLE,
//            //BMAP_DRAWING_POLYLINE,
//            BMAP_DRAWING_POLYGON,
//          ]
//        },
//        circleOptions: this.styleOptions, //圆的样式
//        polylineOptions: this.styleOptions, //线的样式
//        polygonOptions: this.styleOptions, //多边形的样式
//        rectangleOptions: this.styleOptions //矩形的样式
//      });
      //添加鼠标绘制工具监听事件，用于获取绘制结果
//      drawingManager.addEventListener('overlaycomplete', overlaycomplete);

      //槽车标注
      var carIcon = new BMap.Icon(car, new BMap.Size(63, 31));
      this.carMarker = new BMap.Marker(new BMap.Point(120.757272, 30.758201), {icon: carIcon}); // 创建标注
      this.carMarker.setRotation(60);//设置点的旋转角度
      this.carDetail();
      //setInterval(this.pullAlarm,10000);
      this.pullAlarm();
      this.alarmDetail();
      //setInterval(this.efAlarm,10000);


    },
    methods: {
      carDetail(){
        let carContent = `<div>车牌号：浙F209897<br/>所属配送站：嘉兴配送站<br/>储气容量：30<br/>
          <button @click="showTraceModal()">车轨迹</button>
          </div>`;

        let $this = this;
        var tmp = Vue.extend({
          template: carContent,
          methods : {
            showTraceModal(){
              $this.historyTrace = true;
              setTimeout(function () {
                $this.setMap();
              }, 200);
              $this.vertical = '';
            }
          }
        })
        var component = new tmp().$mount();
        //创建检索信息窗口对象
        var searchInfoWindow = null;
        searchInfoWindow = new BMapLib.SearchInfoWindow(this.map, component.$el, {
          title: "槽车信息", //标题
          width: 200, //宽度
          height: 100, //高度
          panel: "panel", //检索结果面板
          enableAutoPan: true, //自动平移
          enableSendToPhone: false,//去除手机图标
          searchTypes: []
        });
        this.carMarker.addEventListener("click", function (e) {
          searchInfoWindow.open($this.carMarker);
        })
        this.map.addOverlay(this.carMarker); //在地图中添加marker
      },
      alarmDetail(){
        let alarmContent = `<div>站点名称：嘉兴加气站<br/>报警时间：2017-09-29 10:49:20<br/>报警类型：泵出口压力高
          <br/>报警因子：泵出口压力<br/><button @click="alarmDetail()">查看详情</button></div>`;
        let $this = this;
        var tmp2 = Vue.extend({
          template: alarmContent,
          methods : {
            alarmDetail(){
              $this.$router.push({path: `/home`});
            },
          }
        })
        var alarmComponent = new tmp2().$mount();
        //创建检索信息窗口对象
        var searchInfoWindow2 = null;
        searchInfoWindow2 = new BMapLib.SearchInfoWindow(this.map, alarmComponent.$el, {
          title: "报警信息", //标题
          width: 200, //宽度
          height: 100, //高度
          panel: "panel", //检索结果面板
          enableAutoPan: true, //自动平移
          enableSendToPhone: false,//去除手机图标
          searchTypes: []
        });
        this.alarmMarker.addEventListener("click", function (e) {
          searchInfoWindow2.open($this.alarmMarker);
        })
        this.map.addOverlay(this.alarmMarker); //在地图中添加marker
      },
      showTrace(orderNum){
        let $this = this;
        console.log(this.historyMap);
        console.log(orderNum);
        var data = [{longitude:120.757278,latitude:30.758201},{longitude:120.757288,latitude:30.758202},{longitude:120.757298,latitude:30.758205}]
        for(var i=0;i<data.length;i++){
          var po = new BMap.Point(parseFloat(data[i].longitude),parseFloat(data[i].latitude));
          //获取所有点位置
          this.points.push(po);
          this.start =new BMap.Point(parseFloat(data[0].longitude),parseFloat(data[0].latitude));
        }

        var icon = new BMap.Icon(car, new BMap.Size(20, 60));
        var tankCar= new BMap.Marker(this.start,{icon:icon});
        var label = new BMap.Label("", {
          offset : new BMap.Size(60, 20)
        });
        label.setStyle({                                   //给label设置样式，任意的CSS都是可以的
          color:"black",                   //颜色
          fontSize:"12px",               //字号
          backgroundColor:"#fff",
          opacity: "0.5",
          border: "1px solid black"
        });
        label.setContent(`经度: ${this.start.lng} <br/>纬度:${this.start.lat}`)
        tankCar.setLabel(label);
        this.historyMap.addOverlay(tankCar);

        var view = this.historyMap.getViewport(this.points);//返回最佳视野
        this.historyMap.centerAndZoom(view.center, view.zoom);
//        var centerPoint = new BMap.Point(
//          (this.points[0].lng + this.points[this.points.length - 1].lng) / 2,
//          (this.points[0].lat + this.points[this.points.length - 1].lat) / 2);
//        this.historyMap.panTo(centerPoint);//地图移动到此轨迹的中心点位置

        var strokePoints = this.points;
        console.log(JSON.stringify(strokePoints));
        var polyline =  new BMap.Polyline(strokePoints, {strokeColor: "red", strokeWeight: 6, strokeOpacity: 0.5});
        this.historyMap.addOverlay(polyline);

      },
      setMap(){
        this.historyMap = new BMap.Map("historyMap", {enableMapClick: false});
        this.historyMap.centerAndZoom(new BMap.Point(120.757278, 30.758204), 15);  // 初始化地图,设置中心点坐标和地图级别
        this.historyMap.setCurrentCity("嘉兴");          // 设置地图显示的城市 此项是必须设置的
        this.historyMap.enableScrollWheelZoom(true);     //开启鼠标滚轮缩放
        this.historyMap.addControl(new BMap.NavigationControl());//左上角，添加默认缩放平移控件
        this.historyMap.enableKeyboard(true);//启动键盘操作
      },
      pullAlarm(){
        var alarmIcon = new BMap.Icon(warning,new BMap.Size(40, 40));
        this.alarmMarker = new BMap.Marker(new BMap.Point(120.762292, 30.769210), {icon: alarmIcon}); // 创建标注
        this.map.addOverlay(this.alarmMarker); // 将标注添加到地图中
      },
      efAdd(){
        if (this.mlnglat.length == 0) {
          alert("请先设置电子围栏！");
        } else {
          alert(this.mlnglat);
        }
      },
      efDelete(){
        for(var i = 0; i < this.overlays.length; i++){
          this.map.removeOverlay(this.overlays[i]);
        }
        this.overlays.length = 0
      },
//      efAlarm(){
//        if(BMapLib.GeoUtils.isPointInPolygon(new BMap.Point(120.757272, 30.758201), new BMap.Polyline(this.mlnglat))){
//          alert('越界');
//          console.log('危险');
//        }else{
//          console.log('安全');
//        }
//      },


    }


  }


</script>
<style scoped>
  #allmap {
    width: 100%;
    height: 90vh;
    overflow: hidden;
    margin: 0;
    font-family: "微软雅黑";
  }
  .modalBody{

    height:80vh;
  }
  div#header {
    padding-right: 13px;
  }

  .checkItem{
    padding: 5px 0;
  }
  .layout{
    border: 1px solid #d7dde4;
    background: #f5f7f9;
    position: relative;
  }
  .layout-ceiling{
    background: #ffffff;
    /*padding: 20px 0;*/
    overflow: hidden;
  }
  .layout-ceiling-main{
    float: right;
    margin-right: 15px;
    padding-top: 10px;
  }
  .layout-ceiling-main a{
    color: #31A4E0;
    padding-left: 20px;
  }
  .layout-ceiling-main a i{
    padding-right: 6px;
  }
</style>
